package com.huang.weic.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.huang.weic.service.VodService;
import com.huang.weic.utils.InitVodClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URL;
import java.util.List;

@Service
public class VodServiceImpl implements VodService {


    private  String KEYID="LTAI5tF1ytdiWCQR71xYekgF";
    private  String KEYSECRET="ePZPqurstp6eZjmACzi8hw79Z5LjWp";



    @Override
    public String uploadVideo(MultipartFile file) {
        try {
            //accessKeyId, accessKeySecret
            //fileName：上传文件原始名称
            String fileName = file.getOriginalFilename();
            //title：上传之后显示名称
            String title = fileName.substring(0, fileName.lastIndexOf(".")); //名字随便取
            //inputStream：上传文件输入流
            InputStream inputStream = file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(KEYID, KEYSECRET, title, fileName, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);

            String videoId = null;
            if (response.isSuccess()) {
                videoId = response.getVideoId();
            } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
                videoId = response.getVideoId();
            }
            return videoId;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String getVideoUrl(String videoId) {
        //初始化,传入key和密钥
        DefaultAcsClient client = InitVodClient.initVodClient(KEYID, KEYSECRET);

        //1.根据视频ID获取视频播放地址
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        //2.创建获取视频地址 request和response
        GetPlayInfoResponse response = new GetPlayInfoResponse();
        //3.向request对象里面设置id
        request.setVideoId(videoId);

        String url="";
        try {
            response = client.getAcsResponse(request);
            List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();

            //播放地址
            for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
               url= playInfo.getPlayURL()+url;
            }
        } catch (Exception e) {

        }
        return url;
    }
}